package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.service.BoardService;
import io.swagger.models.auth.In;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/board")
public class BoardController {
//    从设置中读取，如果没有配置，默认值为9

    @Value("${bit-forum.index.board-num:9}")
    private Integer indexBoardNum;
    @Resource
    private BoardService boardService;

    @GetMapping("/topList")
    public AppResult<List<Board>> topList(){
        log.info("首页板块个数为："+indexBoardNum);
        //调用Service查询结果
        List<Board> boards=boardService.selectByNum(indexBoardNum);
        //判断是否为空
        if(boards==null){
            boards=new ArrayList<>();
        }
        //返回结果
        return  AppResult.success(boards);
    }

    @GetMapping("/getById")
    public AppResult<Board> getById(@RequestParam("id") @NonNull Long id){
        //调用Service
        Board board=boardService.selectById(id);
        //对查询结果进行校验,板块不存在或者是已删除
        if (board==null||board.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        return AppResult.success(board);
    }
}
